package com.ruoyi.channel.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.channel.domain.TChannelInfo;
import com.ruoyi.channel.domain.bo.TChannelInfoBo;
import com.ruoyi.channel.domain.vo.TChannelInfoVo;
import com.ruoyi.channel.mapper.TChannelInfoMapper;
import com.ruoyi.channel.service.ITChannelInfoService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.customer.domain.TRevieweInfo;
import com.ruoyi.customer.domain.vo.TRevieweInfoVo;
import com.ruoyi.customer.mapper.TRevieweInfoMapper;
import com.ruoyi.system.service.ISysRegionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.util.CollectionUtils;

/**
 * 渠道管理Service业务层处理
 *
 * @author zr
 * @date 2023-08-05
 */
@RequiredArgsConstructor
@Service
public class TChannelInfoServiceImpl implements ITChannelInfoService {

    private final TChannelInfoMapper baseMapper;

    private final ISysRegionService sysRegionService;

    private final TRevieweInfoMapper tRevieweInfoMapper;

    /**
     * 查询渠道管理
     */
    @Override
    public TChannelInfoVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询渠道管理列表
     */
    @Override
    public TableDataInfo<TChannelInfoVo> queryPageList(TChannelInfoBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TChannelInfo> lqw = buildQueryWrapper(bo);
        Page<TChannelInfoVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        List<TChannelInfoVo> records = result.getRecords().stream().peek(tChannelInfoVo -> {
            // 使用缓存处理地市
            String province = tChannelInfoVo.getProvinceCode();
            if (StringUtils.isNotBlank(province)) {
                tChannelInfoVo.setProvinceCode(sysRegionService.getRegionByCode(province).getName());
            }
            String city = tChannelInfoVo.getCityCode();
            if (StringUtils.isNotBlank(city)) {
                tChannelInfoVo.setCityCode(sysRegionService.getRegionByCode(city).getName());
            }
            String county = tChannelInfoVo.getCountyCode();
            if (StringUtils.isNotBlank(county)) {
                tChannelInfoVo.setCountyCode(sysRegionService.getRegionByCode(county).getName());
            }
        }).collect(Collectors.toList());
        return TableDataInfo.build(result.setRecords(records));
    }

    /**
     * 查询渠道管理列表
     */
    @Override
    public List<TChannelInfoVo> queryList(TChannelInfoBo bo) {
        LambdaQueryWrapper<TChannelInfo> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TChannelInfo> buildQueryWrapper(TChannelInfoBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TChannelInfo> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getName()), TChannelInfo::getName, bo.getName());
        lqw.like(StringUtils.isNotBlank(bo.getCode()), TChannelInfo::getCode, bo.getCode());
        lqw.like(StringUtils.isNotBlank(bo.getAddress()), TChannelInfo::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getLeader()), TChannelInfo::getLeader, bo.getLeader());
        lqw.like(StringUtils.isNotBlank(bo.getMobilePhone()), TChannelInfo::getMobilePhone, bo.getMobilePhone());
        lqw.eq(StringUtils.isNotBlank(bo.getProvinceCode()), TChannelInfo::getProvinceCode, bo.getProvinceCode());
        lqw.eq(StringUtils.isNotBlank(bo.getCityCode()), TChannelInfo::getCityCode, bo.getCityCode());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), TChannelInfo::getStatus, bo.getStatus());
        return lqw;
    }

    /**
     * 新增渠道管理
     */
    @Override
    public Boolean insertByBo(TChannelInfoBo bo) {
        TChannelInfo add = BeanUtil.toBean(bo, TChannelInfo.class);
        validEntityBeforeSave(add, false);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改渠道管理
     */
    @Override
    public Boolean updateByBo(TChannelInfoBo bo) {
        TChannelInfo update = BeanUtil.toBean(bo, TChannelInfo.class);
        validEntityBeforeSave(update, true);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TChannelInfo entity, boolean flag) {
        LambdaQueryWrapper<TChannelInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TChannelInfo::getDelFlag, "0");
        queryWrapper.eq(TChannelInfo::getCode, entity.getCode());
        if (flag) {
            queryWrapper.ne(TChannelInfo::getId, entity.getId());
        }
        Long count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new ServiceException("该渠道的编码已经存在!");
        }
    }

    /**
     * 批量删除渠道管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
            // ids.stream()
            for (Long id : ids) {
                QueryWrapper<TRevieweInfo> query = Wrappers.query();
                query.apply("in_bank in ( " + id + " )" + " OR " + "bank in ( " + id + " )");
                List<TRevieweInfoVo> tRevieweInfoVos = tRevieweInfoMapper.selectVoList(query);
                if (!CollectionUtils.isEmpty(tRevieweInfoVos)) {
                    throw new ServiceException("存在再审件记录，不可删除");
                }
            }
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
